package com.nengjiang.wsplayer.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.nengjiang.wsplayer.Config;
import com.nengjiang.wsplayer.EventListener;
import com.nengjiang.wsplayer.R;
import com.nengjiang.wsplayer.base.BaseThemeActivity;
import com.nengjiang.wsplayer.bean.LoginRequest;
import com.nengjiang.wsplayer.bean.LoginResponse;
import com.nengjiang.wsplayer.oksocket.Event;
import com.nengjiang.wsplayer.oksocket.OkManager;

public class LoginActivity extends BaseThemeActivity {
    public static final String TAG = "LoginActivity";

    private EventListener eventListener;

    private EditText mEtUserName;
    private EditText mEtPwd;
    private TextView settingBtn;
    private Button login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        eventListener = new EventListener() {
            @Override
            public void onLoginRes(LoginResponse message) {
                Log.i(TAG, "onLoginRes");
                if (message != null) {
                    if (message.data.errorCode == 0) {
                        showToast("登录成功");
                        OkManager.getInstance().getHeartbeatInterval();
                        goHome();
                    } else {
                        showToast("" + message.data.errorMsg);
                    }
                }

            }

            @Override
            public void onConnectionSuccess() {
//                showToast("链接服务器成功");
            }
        };


        OkManager.getInstance().addEventListener(eventListener);
    }


    private void initView() {

        mEtUserName = findViewById(R.id.et_username);
        mEtPwd = findViewById(R.id.et_password);
        login = findViewById(R.id.login);
        settingBtn = findViewById(R.id.tv_server_config);

        settingBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goConfig();
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logins();
            }
        });
    }

    private void goConfig(){
        Intent intent = new Intent(this, ConfigUrlActivity.class);
        startActivity(intent);
    }


    private void goHome() {
        Intent intent = new Intent(this, WaitActivity.class);
        startActivity(intent);
        finish();
    }

    Handler handler = new Handler();

    @Override
    protected void onResume() {
        super.onResume();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                logins();
//            }
//        }, 2000);
    }

    public void logins() {
        LoginRequest loginRequest = new LoginRequest(Event.EVENT_LOGIN_REQUEST);

        LoginRequest.LoginData loginData = new LoginRequest.LoginData();
        loginData.account = mEtUserName.getText().toString().trim();
        loginData.pwd = mEtPwd.getText().toString().trim();
        loginRequest.data = loginData;

        OkManager.getInstance().sendMessage(loginRequest.toJson());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkManager.getInstance().removeEventListener(eventListener);
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        Log.e("demo2", event.getAction() + "," + event.getKeyCode());
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
                View rootView = getWindow().getDecorView();
                View currentFocus = rootView.findFocus();
                Log.e("demo2", "setting:" + settingBtn.getId());
                Log.e("demo2", "username:" + mEtUserName.getId());
                Log.e("demo2", "password:" + mEtPwd.getId());
                Log.e("demo2", "id:" + currentFocus.getId());
                Log.e("demo2", "isShowing:" + isSoftShowing());
                if(currentFocus.getId() == R.id.tv_server_config){
                    if(isSoftShowing() == false) {
                        showOrHide(this);
                        mEtUserName.requestFocus();
                    }
                    return true;
                }
                if (currentFocus.getId() == R.id.et_username) {
                    if(isSoftShowing() == false) {
                        showOrHide(this);
                        mEtPwd.requestFocus();
                    }
                    return true;
                }
                if (currentFocus.getId() == R.id.et_password) {
                    if(isSoftShowing() == false) {
                        login.requestFocus();
                    }
                    return true;
                }
            }

            if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
                View rootView = getWindow().getDecorView();
                View currentFocus = rootView.findFocus();
                Log.e("demo2", "id:" + currentFocus.getId());
                Log.e("demo2", "isShowing:" + isSoftShowing());
                if (currentFocus.getId() == R.id.et_username) {
                    if(isSoftShowing() == false) {
                        settingBtn.requestFocus();
                    }
                    return true;
                }
                if (currentFocus.getId() == R.id.et_password) {
                    if(isSoftShowing() == false) {
                        showOrHide(this);
                        mEtUserName.requestFocus();
                    }
                    return true;
                }

                if(currentFocus.getId() == R.id.login){
                    if(isSoftShowing() == false) {
                        showOrHide(this);
                        mEtPwd.requestFocus();
                    }
                    return true;
                }
            }


        }
        return super.dispatchKeyEvent(event);
    }

    //如果输入法在窗口上已经显示，则隐藏，反之则显示
    public static void showOrHide(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //view为接受软键盘输入的视图，SHOW_FORCED表示强制显示
    public static void showOrHide(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        //  imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);//SHOW_FORCED表示强制显示
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }

    //调用隐藏系统默认的输入法
    public static void showOrHide(Context context, Activity activity) {
        ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //获取输入法打开的状态
    private boolean isSoftShowing() {
        //获取当屏幕内容的高度
        int screenHeight = this.getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        //DecorView即为activity的顶级view
        this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        //考虑到虚拟导航栏的情况（虚拟导航栏情况下：screenHeight = rect.bottom + 虚拟导航栏高度）
        //选取screenHeight*2/3进行判断
        Log.i("demo2","screenHigh: " + screenHeight + " rectViewBom : " + rect.bottom );
        return screenHeight * 2 / 3 > rect.bottom;
    }
}